package org.ns.summer.classpath.classreader.basicinfo.attribute;

import org.ns.summer.classpath.classreader.ConstantPool;
import org.ns.summer.classpath.classreader.basicinfo.BasicInfo;
import org.ns.summer.classpath.classreader.basictype.U1;
import org.ns.summer.classpath.classreader.basictype.U2;
import org.ns.summer.classpath.classreader.basictype.U4;
import org.ns.summer.classpath.classreader.constantinfo.ConstantUtf8;

import java.io.InputStream;


public class AttributeInfo extends BasicInfo {
	public int nameIndex;
	public int length;
	public short[] info;

	public static final String CODE = "Code";

	public AttributeInfo(ConstantPool cp, int nameIndex) {

		super(cp);
		this.nameIndex = nameIndex;
	}

	public AttributeInfo(ConstantPool cp) {
		super(cp);
	}

	@Override
	public void read(InputStream inputStream) {
		length = (int) U4.read(inputStream);
		info = new short[length];
		for (int i = 0; i < length; i++) {
			info[i] = U1.read(inputStream);
		}
	}
	public void read2(InputStream inputStream) {
		nameIndex = U2.read(inputStream);
		length = (int) U4.read(inputStream);
		info = new short[length];
		for (int i = 0; i < length; i++) {
			info[i] = U1.read(inputStream);
		}
	}

	public static AttributeInfo getAttribute(ConstantPool cp, InputStream inputStream) {
		int nameIndex = U2.read(inputStream);
		String name = ((ConstantUtf8) cp.cpInfo[nameIndex]).value;
		switch (name) {
		case CODE:
			return new CodeAttribute(cp, nameIndex);
		}
		return new AttributeInfo(cp, nameIndex);

	}
}
